<script setup>
import { ref, onMounted } from 'vue'
import Info from './info.vue'
// import AssignRole from './components/assignRole.vue'

import { useConfirm } from '@/hooks/useConfirm'

// import tableData from '~mock/role'
import { getRoleList, deleteRole,roleUpdateMenu,roleMenu } from '@/api/role'
import { menutree } from '@/api/menu'


// 表单状态
const filterState = ref(true)
// 表单数据
const formDataPage = {
  pageNum: 1,
  pageSize: 10,
  size: 10
}
const tableData = ref({})
const loadData = async () => {
  try {
    // Object.assign({}, formData, startDate, endDate)
    const r = await getRoleList(formDataPage.value)
    if (r.code == 200) {
      tableData.value = r.data
      ElMessage({
        type: 'success',
        message: '获取列表成功'
      })
    } else {
      ElMessage.error(r.data.msg)
    }
  } catch {
    ElMessage.error('请稍后再试')
  }
}

onMounted(async() => {
  loadData()
  let r=await menutree()
  rmenu.value=r.data
  console.log("222",rmenu.value)
})
// 分页
const onSizeChange = (val) => {
  console.log(`${val} items per page`)
}
const onCurrentChange = (val) => {
  console.log(`current page: ${val}`)
}

// 角色编辑
const infoRef = ref()
const onUserInfo = (row) => {
  console.log('row', row)
  // console.log(row)
  infoRef.value.stateDrawer = true
  if (row) {
    infoRef.value.formData = row
  }
}

// 角色删除
const onDelete = (row) => {
  ElMessageBox.confirm('确定删除该条数据吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      console.log('进入删除接口')
      const r = await deleteRole({ id: row.id })
      if (r.code == 200) {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        loadData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '用户取消'
      })
    })
}

const userState = ref('')
const userStateOption = [
  {
    value: 1,
    label: '正常'
  },
  {
    value: 0,
    label: '禁用'
  }
]

// 批量选择
let ids = ref([])
const onSelectionChange = (val) => {
  ids.value = val
}



const showchange=ref(false)
//菜单信息
const rmenu=ref({})
//角色选择的菜单和权限
const mids=ref([])
const onMenuSet=async (row)=>{
  //请求接口 查询当前角色对应的菜单和权限
  let r2=await roleMenu({rid:row.id})
  mids.value=r2.data
  rMenuChange.value.id=row.id
  showchange.value=true
}
// 树形下拉框的数据的字段格式
const props = {
  children: 'children',
  label: 'authName',
  value: 'id'
}
const rMenuChange=ref({
  id:0,
  mids:[],
  pids:[]
})
const treeMenu=ref({})
const treePerm=ref({})

const changeMenu=async ()=>{
  //请求接口 设置角色对应的菜单和权限
  rMenuChange.value.mids=new Array()
  //获取选中的菜单ids
  rMenuChange.value.mids.push(...treeMenu.value.getCheckedKeys())
  rMenuChange.value.pids=new Array()
  //获取选中的权限ids
  rMenuChange.value.pids.push(...treePerm.value.getCheckedKeys())
  //请求接口 角色权限分配
  let r=await roleUpdateMenu(rMenuChange.value)
  if(r.code==200){
    ElMessage.success("角色权限分配成功")
    showchange.value=false;
  }else{
    ElMessage.info(r.data)
  }
}
</script>
<template>
  <Box>
    <!-- 逻辑层 -->
    <Info ref="infoRef" @flush="loadData" />
    <!-- <AssignRole ref="assignRoleRef" /> -->
    <!-- 逻辑层 -->

    <!-- 筛选 -->
    <template #filter v-if="filterState">
      <el-form :inline="true" :model="formDataPage">
        <el-form-item label="角色名称">
          <el-input placeholder="请输入角色名称" v-model="formDataPage.username" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="userState" placeholder="角色状态" style="width: 120px">
            <el-option
              v-for="item in userStateOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建于">
          <el-date-picker
            v-model="formDataPage.created_at_temp"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary"> <span class="iconfont icon-sousuo"></span>搜索 </el-button>
          <el-button type="default"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </template>
    <!-- 筛选 -->
    <!-- 内容 -->
    <!-- 按钮组 -->
    <el-row>
      <el-col :span="12">
        <el-button type="primary" @click="onUserInfo(null)">
          <span class="iconfont icon-jiahao"></span>添加
        </el-button>
        <el-button type="danger" :disabled="!ids.length">
          <span class="iconfont icon-shanchu"></span>删除
        </el-button>
        <!-- <el-button type="success" @click="onUserInfo" :disabled="ids.length !== 1">
            <span class="iconfont icon-bianji"></span>修改
          </el-button> -->
        <el-button type="warning" @click="$message.warning('演示数据，禁止操作')">
          <span class="iconfont icon-xiazai-"></span>导出
        </el-button>
      </el-col>

      <el-col :span="12" style="text-align: right">
        <el-button circle @click="filterState = !filterState">
          <span class="iconfont icon-sousuo"></span>
        </el-button>
        <el-button circle>
          <span class="iconfont icon-shuaxin"></span>
        </el-button>
      </el-col>
    </el-row>
    <!-- 按钮组 -->
    <!-- 表格 -->
    <el-table :data="tableData.list" :border="true" @selection-change="onSelectionChange">
      <el-table-column type="selection" align="center" fixed="left"></el-table-column>
      <el-table-column label="序号" prop="orderId" align="center" width="60"></el-table-column>
      <el-table-column
        label="角色编码"
        prop="roleCode"
        align="center"
        width="200"
      ></el-table-column>
      <el-table-column label="角色名称" prop="roleName" align="center" width="200">
        <!-- <template #default="scope">
          <span>{{ scope.row.role_name }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="排序" prop="orderId" align="center" width="200"></el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scoped" prop="state">
          <el-switch
            v-model="scoped.row.state"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-text="正常"
            inactive-text="禁用"
            :active-value=0
            :inactive-value=1
          />
        </template>
      </el-table-column>
      <el-table-column label="说明" prop="description" align="center" width="200"></el-table-column>
      <el-table-column
        label="创建于"
        prop="created_at"
        align="center"
        width="200"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scoped">
          <el-button type="primary" link size="small" @click="onUserInfo(scoped.row)">
            <span class="iconfont icon-bianji"></span>修改
          </el-button>
          <el-button type="primary" link size="small" @click="onDelete(scoped.row)">
            <span class="iconfont icon-shanchu"></span>删除
          </el-button>
          <el-button type="primary" link size="small" @click="onMenuSet(scoped.row)">
            <span class="iconfont icon-shanchu"></span>权限分配
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格 -->
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="formDataPage.pagenum"
      v-model:page-size="formDataPage.pagesize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="6"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    />
    <!-- 分页 -->
    <!-- 内容 -->

    <div v-if="showchange">
      <el-dialog
        v-model="showchange"
        :title="角色权限分配"
        width="600"
        :before-close="() => (showchange = false)"
      >
        <!-- 内容 -->
        <el-form size="large" label-width="80">
          <el-row>
            <el-col :span="12">
              <el-form-item label="角色菜单">
                <el-tree
                  :data="rmenu.menus"
                  check-strictly="true"
                  :default-checked-keys="mids"
                  :props="props"
                  ref="treeMenu"
                  node-key="id"
                  show-checkbox
                ></el-tree>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色权限">
                <el-tree
                  :data="rmenu.perms"
                  check-strictly="true"
                  node-key="id"
                  ref="treePerm"
                  :default-checked-keys="mids"
                  :props="props"
                  show-checkbox
                ></el-tree>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="">
            <el-button type="primary" @click="changeMenu">确定</el-button>
            <el-button type="default" @click="showchange = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </Box>
</template>
